package com.ruicar.afs.cloud.basic.detail.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.creditchange.vo.ContractBasicListVO;
import com.ruicar.afs.cloud.basic.detail.vo.*;
import com.ruicar.afs.cloud.basic.feign.CaseForLoanBeforeInfoFeign;
import com.ruicar.afs.cloud.basic.proceeds.pay.service.BasicPaymentPoolService;
import com.ruicar.afs.cloud.basic.proceeds.pay.service.BasicPaymentRecordService;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.BasicCustBaseInfoVo;
import com.ruicar.afs.cloud.common.modules.contract.cms.vo.CustBaseInfoVo;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.api.dto.OverpaymentDifferenceDTO;
import com.ruicar.afs.cloud.manage.api.feign.repayment.RepaymentDateChangeService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author HuangTao
 * @Date 2020/9/10 14:29
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/contractDetailDedicated")
@AllArgsConstructor
public class ContractDetailDedicatedController {
    private final BasicMainInfoService basicMainInfoService;
    private final BasicReceiptRecordService basicReceiptRecordService;
    private final BasicAffiliatedUnitService basicAffiliatedUnitService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicFinancialAgreementService basicFinancialAgreementService;
    private final BasicCarDetailsService basicCarDetailsService;
    private final BasicProductParamService basicProductParamService;
    private final RepaymentDateChangeService repaymentDateChangeService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final ContractFeginConfig contractFeginConfig;
    private final BasicChannelInfoService basicChannelInfoService;
    private final BasicCustPersonalDetailService basicCustPersonalDetailService;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final BasicCustContactsService basicCustContactsService;
    private final BasicCustAddressDetailsService basicCustAddressDetailsService;
    private final BasicCustContactDetailsService basicCustContactDetailsService;
    private final BasicPenaltyInterestService basicPenaltyInterestService;
    private final BasicExpenseRecordService basicExpenseRecordService;
    private final BasicBankCardService basicBankCardService;
    private final CaseForLoanBeforeInfoFeign caseForLoanBeforeInfoFeign;
    private final BasicFinancingItemsService basicFinancingItemsService;
    private final BasicPaymentRecordService basicPaymentRecordService;
    private final BasicPaymentPoolService basicPaymentPoolService;
    private final BasicDebitInfoService basicDebitInfoService;

    @ApiOperation(value = "多条件查询合同列表")
    @PostMapping("/list")
    public IResponse<IPage<List<ContractBasicListVO>>> ContractList(@RequestBody QueryListVO query) {
        Page page = new Page(query.getPageNumber(), query.getPageSize());
        IPage<List<QueryListVO>> voList = basicMainInfoService.queryContractInfo(page, query);
        return IResponse.success(voList);
    }

    @ApiOperation(value = "根据合同号码查询合同详细信息")
    @PostMapping("/detail")
    public IResponse<ContractDetailVO> contractDetail(@RequestParam("contractNo") String contractNo) {
        ContractDetailVO vo = new ContractDetailVO();
        RentInfoVO rentInfo = new RentInfoVO();

        //合同信息
        BasicMainInfo basicMainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery().eq(BasicMainInfo::getContractNo, contractNo));
        List<BasicAffiliatedUnit> basicAffiliatedUnits = basicAffiliatedUnitService.list(Wrappers.<BasicAffiliatedUnit>lambdaQuery().eq(BasicAffiliatedUnit::getContractNo, contractNo));
        BasicDebitInfo basicDebitInfo = basicDebitInfoService.getOne(Wrappers.<BasicDebitInfo>query().lambda()
                .eq(BasicDebitInfo::getContractNo, contractNo)
        );

        ContractInfoVO contractInfo = new ContractInfoVO();
        if (EmptyUtils.isNotEmpty(basicDebitInfo.getCurrentAbsoluteOverdue())) {
            Integer currentAbsoluteOverdue = basicDebitInfo.getCurrentAbsoluteOverdue();
            contractInfo.setCurrentAbsoluteOverdue(currentAbsoluteOverdue);
        }
        if (EmptyUtils.isNotEmpty(basicMainInfo)) {
            BeanUtils.copyProperties(basicMainInfo, contractInfo);
            contractInfo.setChannelBelong(basicMainInfo.getChannelBelong());
            //业务合作伙伴信息
            ChannelInfoVO channelInfo = new ChannelInfoVO();
            channelInfo.setChannelName(basicMainInfo.getChannelFullName());
            channelInfo.setChannelType(basicMainInfo.getChannelType());
//            channelInfo.setChannelBelong(basicMainInfo.getChannelBelong());
            vo.setChannelInfo(channelInfo);
        }
        if (EmptyUtils.isNotEmpty(basicAffiliatedUnits) && EmptyUtils.isNotEmpty(basicAffiliatedUnits.get(0).getAffiliatedType())) {
            contractInfo.setAffiliatedType(basicAffiliatedUnits.get(0).getAffiliatedType());
        }
        //客户信息
        List<CustInfoVO> custInfos = basicCustBaseInfoService.queryCustInfo(contractNo);


        if (custInfos.size() == 3) {
            if (custInfos.get(0).getRoleType().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
                if (custInfos.get(1).getRoleType().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
                    CustInfoVO custInfoVO = new CustInfoVO();
                    BeanUtils.copyProperties(custInfos.get(1), custInfoVO);
                    BeanUtils.copyProperties(custInfos.get(2), custInfos.get(1));
                    BeanUtils.copyProperties(custInfoVO, custInfos.get(2));
                }
            }
            if (custInfos.get(0).getRoleType().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
                if (custInfos.get(1).getRoleType().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
                    CustInfoVO custInfoVO = new CustInfoVO();
                    BeanUtils.copyProperties(custInfos.get(0), custInfoVO);
                    BeanUtils.copyProperties(custInfos.get(1), custInfos.get(0));
                    BeanUtils.copyProperties(custInfoVO, custInfos.get(1));
                }
                if (custInfos.get(1).getRoleType().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
                    CustInfoVO custInfoVO = new CustInfoVO();
                    CustInfoVO custInfoVOTwo = new CustInfoVO();
                    BeanUtils.copyProperties(custInfos.get(0), custInfoVO);
                    BeanUtils.copyProperties(custInfos.get(2), custInfos.get(0));
                    BeanUtils.copyProperties(custInfos.get(1), custInfoVOTwo);
                    BeanUtils.copyProperties(custInfoVO, custInfos.get(1));
                    BeanUtils.copyProperties(custInfoVOTwo, custInfos.get(2));
                }
            }
            if (custInfos.get(0).getRoleType().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
                if (custInfos.get(1).getRoleType().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
                    CustInfoVO custInfoVO = new CustInfoVO();
                    CustInfoVO custInfoVOTwo = new CustInfoVO();
                    BeanUtils.copyProperties(custInfos.get(0), custInfoVO);
                    BeanUtils.copyProperties(custInfos.get(1), custInfos.get(0));
                    BeanUtils.copyProperties(custInfos.get(2), custInfoVOTwo);
                    BeanUtils.copyProperties(custInfoVO, custInfos.get(2));
                    BeanUtils.copyProperties(custInfoVOTwo, custInfos.get(1));
                }
                if (custInfos.get(1).getRoleType().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
                    CustInfoVO custInfoVO = new CustInfoVO();
                    BeanUtils.copyProperties(custInfos.get(0), custInfoVO);
                    BeanUtils.copyProperties(custInfos.get(2), custInfos.get(0));
                    BeanUtils.copyProperties(custInfoVO, custInfos.get(2));
                }
            }
        }
        if (custInfos.size() == 2) {
            if (custInfos.get(0).getRoleType().equals(PersonRoleTypeEnum.JOINT_PERSON) || custInfos.get(0).getRoleType().equals(PersonRoleTypeEnum.GUARANTEE_PERSON)) {
                CustInfoVO custInfoVO = new CustInfoVO();
                BeanUtils.copyProperties(custInfos.get(0), custInfoVO);
                BeanUtils.copyProperties(custInfos.get(1), custInfos.get(0));
                BeanUtils.copyProperties(custInfoVO, custInfos.get(1));
            }
        }

        //财务信息
        List<BasicFinancialAgreement> basicFinancialAgreements = basicFinancialAgreementService.list(Wrappers.<BasicFinancialAgreement>lambdaQuery().
                eq(BasicFinancialAgreement::getContractNo, contractNo));
        BasicProductParam basicProductParam = basicProductParamService.getOne(Wrappers.<BasicProductParam>lambdaQuery().
                eq(BasicProductParam::getContractNo, contractNo).eq(BasicProductParam::getAtomKey, AfsEnumUtil.key(ProductAtomEnum.RATE_TYPE)));
        BasicProductParam repaymentType = basicProductParamService.getOne(Wrappers.<BasicProductParam>lambdaQuery().
                eq(BasicProductParam::getContractNo, contractNo).eq(BasicProductParam::getAtomKey, AfsEnumUtil.key(ProductAtomEnum.REPAYMENT_TYPE)));

        //财务信息  CAR车辆信息
        List<FinanceInfoVO> financeInfos = new ArrayList<>();
        FinanceInfoVO financeInfoCar = new FinanceInfoVO();
        FinanceInfoVO financeInfoAdditional = new FinanceInfoVO();
        BigDecimal addAmt = BigDecimal.ZERO;
        if (EmptyUtils.isNotEmpty(basicFinancialAgreements)) {
            for (BasicFinancialAgreement agreement : basicFinancialAgreements) {
                //车款
                if (AssetTypeEnum.CAR_AMT == agreement.getCostType()) {
                    financeInfoCar.setProductName(basicMainInfo.getProductName());
                    financeInfoCar.setType(AssetTypeEnum.CAR_AMT);
                    financeInfoCar.setContractAmt(agreement.getContractAmt());
                    financeInfoCar.setIsLpr(EmptyUtils.isNotEmpty(basicProductParam) ? basicProductParam.getAtomValue() : null);
                    financeInfoCar.setRepaymentType(EmptyUtils.isNotEmpty(repaymentType) ? repaymentType.getAtomValue() : null);
                    financeInfoCar.setDownPayAmt(agreement.getDownPayAmt());
                    financeInfoCar.setDownPayScale(agreement.getDownPayScale());
                    financeInfoCar.setLoanAmt(agreement.getLoanAmt());
                    rentInfo.setTotalDiscountAmt(financeInfoCar.getTotalDiscountAmt());
                    financeInfoCar.setMonthPayAmt(agreement.getMonthPayAmt());
                    financeInfoCar.setCustRate(agreement.getCustRate());
                    financeInfoCar.setSettleRate(agreement.getSettleRate());
                    addAmt = agreement.getAddAmt() == null ? BigDecimal.ZERO : agreement.getAddAmt();
                    financeInfoCar.setDiscountRate(agreement.getSettleRate().subtract(agreement.getCustRate()));
                    BigDecimal tailPayAmt = agreement.getTailPayAmt() == null ? BigDecimal.ZERO : agreement.getTailPayAmt();
                    financeInfoCar.setTailPayAmt(tailPayAmt);
//                    financeInfoCar.setFinancPercent(new BigDecimal(100).subtract(agreement.getDownPayScale()));
                    financeInfoCar.setFinancPercent(agreement.getLoanAmt());
//                    List<BasicFinancingItems> basicFinancingItemsList = basicFinancingItemsService.list(Wrappers.<BasicFinancingItems>query().lambda()
//                            .eq(BasicFinancingItems::getContractNo, contractNo)
//                    );
//                    if (EmptyUtils.isNotEmpty(basicFinancingItemsList) && basicFinancingItemsList.size() > 0) {
//                        for (BasicFinancingItems basicFinancingItems : basicFinancingItemsList) {
//                            if (EmptyUtils.isNotEmpty(basicFinancingItems.getFinanceItemAmt())) {
//                                if (EmptyUtils.isEmpty(basicFinancingItems.getUpperId())) {
//                                    addAmt = addAmt.add(basicFinancingItems.getFinanceItemAmt());
//                                } else {
//                                    BigDecimal financeItemAmt = basicFinancingItems.getFinanceItemAmt();
//                                    financeItemAmt = BigDecimal.ZERO;
//                                    addAmt = addAmt.add(financeItemAmt);
//                                }
//                            }
//                        }
//                    }

                } else {


                    //附加贷款
                    financeInfoAdditional.setProductName(basicMainInfo.getProductName());
                    financeInfoAdditional.setType(AssetTypeEnum.ADDITIONAL);
                    addAmt = agreement.getContractAmt() == null ? BigDecimal.ZERO : agreement.getContractAmt();
                    financeInfoAdditional.setContractAmt(agreement.getContractAmt());
                    financeInfoAdditional.setIsLpr(EmptyUtils.isNotEmpty(basicProductParam) ? basicProductParam.getAtomValue() : null);
                    financeInfoAdditional.setRepaymentType(EmptyUtils.isNotEmpty(repaymentType) ? repaymentType.getAtomValue() : null);
                    financeInfoAdditional.setDownPayAmt(agreement.getDownPayAmt());
                    financeInfoAdditional.setDownPayScale(agreement.getDownPayScale());
                    financeInfoAdditional.setLoanAmt(agreement.getLoanAmt());
                    financeInfoAdditional.setMonthPayAmt(agreement.getMonthPayAmt());
                    financeInfoAdditional.setCustRate(agreement.getCustRate());
                    financeInfoAdditional.setSettleRate(agreement.getSettleRate());
                    financeInfoAdditional.setDiscountRate(agreement.getSettleRate().subtract(agreement.getCustRate()));
                    BigDecimal tailPayAmt = agreement.getTailPayAmt() == null ? BigDecimal.ZERO : agreement.getTailPayAmt();
                    financeInfoAdditional.setTailPayAmt(tailPayAmt);
//                    financeInfoAdditional.setFinancPercent(new BigDecimal(100).subtract(agreement.getDownPayScale()));
                    financeInfoAdditional.setFinancPercent(agreement.getLoanAmt());
                }
            }
            //财务信息  TOTAL总
            BasicFinancialAgreement agreement = new BasicFinancialAgreement();
            agreement = agreement.sum(basicFinancialAgreements);
            FinanceInfoVO financeInfoTotal = new FinanceInfoVO();
            BeanUtils.copyProperties(agreement, financeInfoTotal);
            financeInfoTotal.setProductName(basicMainInfo.getProductName());
            financeInfoTotal.setType(AssetTypeEnum.TOTAL);
            financeInfoTotal.setAddAmt(addAmt);
            financeInfoTotal.setIsLpr(EmptyUtils.isNotEmpty(basicProductParam) ? basicProductParam.getAtomValue() : null);
            financeInfoTotal.setRepaymentType(EmptyUtils.isNotEmpty(repaymentType) ? repaymentType.getAtomValue() : null);
            Map<String, String> heards = new HashMap<>();
            heards.put(AfsEnumUtil.key(ContractFeginParamEnum.MANAGE_CLIENT_ID), contractFeginConfig.getManageClientId());
            heards.put(AfsEnumUtil.key(ContractFeginParamEnum.MANAGE_CLIENT_SECRET), contractFeginConfig.getManageClientSecret());
            IResponse<OverpaymentDifferenceDTO> response = repaymentDateChangeService.queryOverpaymentOrDifference(contractNo, heards);
            if ("0000".equals(response.getCode()) && EmptyUtils.isNotEmpty(response.getData())) {
                OverpaymentDifferenceDTO overpaymentDifference = response.getData();
                if (OverpaymentDifferenceTypeEnum.DIFFERENCE == overpaymentDifference.getType()) {
                    financeInfoTotal.setDifference(overpaymentDifference.getAmount());
                } else {
                    financeInfoTotal.setOverpayment(overpaymentDifference.getAmount());
                }
            }

            financeInfos.add(financeInfoCar);
            financeInfos.add(financeInfoAdditional);
            financeInfos.add(financeInfoTotal);
        }

        //租金明细信息
        List<RentInfoVO> rentInfoVOS = basicRepaymentPlanService.queryRepaymentInfo(contractNo, null);
//        List<BasicExpenseRecord> basicExpenseRecords = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>lambdaQuery().
//                eq(BasicExpenseRecord::getContractNo, contractNo));
        List<BasicReceiptRecord> basicReceiptRecordList = basicReceiptRecordService.list(Wrappers.<BasicReceiptRecord>query().lambda()
                .eq(BasicReceiptRecord::getContractNo, contractNo)
                .orderByDesc(BasicReceiptRecord::getSucceedTime)
        );

        if (EmptyUtils.isNotEmpty(rentInfoVOS)) {
            rentInfo = rentInfoVOS.get(0);
            BasicReceiptRecord basicReceiptRecord = null;
            if (basicReceiptRecordList.size() > 0 && EmptyUtils.isNotEmpty(basicReceiptRecordList)) {
                basicReceiptRecord = basicReceiptRecordList.get(0);
                rentInfo.setSucceedTime(basicReceiptRecord.getSucceedTime());
                rentInfo.setArriveAmt(basicReceiptRecord.getArriveAmt());
            }
//            if (EmptyUtils.isNotEmpty(basicRepaymentPlanList) && basicRepaymentPlanList.size() > 0) {
//                for (BasicRepaymentPlan basicRepaymentPlan : basicRepaymentPlanList) {
//                    BigDecimal receivableRent = basicRepaymentPlan.getReceivableRent();
//                    rentInfo.setReceivableTotal(receivableRent.add(rentInfo.getReceivableTotal()));
//                    BigDecimal receivableInterest = basicRepaymentPlan.getReceivableInterest();
//                    rentInfo.setInterestTotal(rentInfo.getReceivableTotal().add(receivableInterest));
//                }
//            }
        }
        //资产信息
        List<BasicCarDetails> basicCarDetails = basicCarDetailsService.list(Wrappers.<BasicCarDetails>lambdaQuery().
                eq(BasicCarDetails::getContractNo, contractNo));
        if (EmptyUtils.isNotEmpty(basicCarDetails)) {
            AssetsInfoVO assetsInfo = JSON.parseObject(JSON.toJSONString(basicCarDetails.get(0)), AssetsInfoVO.class);
            vo.setAssetsInfo(EmptyUtils.isNotEmpty(assetsInfo) ? assetsInfo : new AssetsInfoVO());
        }

        //挂靠信息
        List<BasicAffiliatedUnit> affiliatedUnits = basicAffiliatedUnitService.list(Wrappers.<BasicAffiliatedUnit>lambdaQuery().
                eq(BasicAffiliatedUnit::getContractNo, contractNo));
        if (EmptyUtils.isNotEmpty(affiliatedUnits)) {
            AffiliatedInfoVO affiliatedInfo = JSON.parseObject(JSON.toJSONString(affiliatedUnits.get(0)), AffiliatedInfoVO.class);
            vo.setAffiliatedInfo(EmptyUtils.isNotEmpty(affiliatedInfo) ? affiliatedInfo : new AffiliatedInfoVO());
        }
        vo.setContractInfo(contractInfo);
        vo.setCustInfo(EmptyUtils.isNotEmpty(custInfos) ? custInfos : Lists.newArrayList());
        vo.setFinanceInfo(financeInfos);
        vo.setRentInfo(EmptyUtils.isNotEmpty(rentInfo) ? rentInfo : new RentInfoVO());

        return IResponse.success(vo);
    }

    @ApiOperation(value = "根据合同号码查询渠道信息")
    @PostMapping("/channelInfo")
    public IResponse<BasicChannelInfo> channelInfo(@RequestParam("contractNo") String contractNo) {
        BasicChannelInfo basicChannelInfo = basicChannelInfoService.getOne(Wrappers.<BasicChannelInfo>lambdaQuery().
                eq(BasicChannelInfo::getContractNo, contractNo));
        return IResponse.success(basicChannelInfo);
    }

    @ApiOperation(value = "根据合同号码查询主借人/共借人/担保人基本信息（custRole参数不传默认查询主借人的基本信息）")
    @PostMapping("/custBaseInfo")
    public IResponse<BasicCustBaseInfoVo> custBaseInfo(@RequestParam("contractNo") String contractNo,
                                                       @RequestParam(value = "custRole", defaultValue = "MAIN_PERSON") String custRole) {

        if (EmptyUtils.isEmpty(contractNo)) {
            return IResponse.fail("输入参数不得为空");
        }
        /**  贷后系统中的主借人客户号 by ZC.GUO  **/
        BasicCustBaseInfoVo afterLoanInfo = new BasicCustBaseInfoVo();
        String custNo = null;
        List<String> custNoList = basicCustBaseInfoService.fingCustByNoAndCust(contractNo, custRole);
        if (EmptyUtils.isNotEmpty(custNoList)) {
            custNo = custNoList.get(0);
        }
        if (EmptyUtils.isNotEmpty(custNo)) {
            BasicCustBaseInfo custBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda().eq(BasicCustBaseInfo::getCustNo, custNo));
            afterLoanInfo.setCustName(custBaseInfo.getCustName());
            afterLoanInfo.setPhone(custBaseInfo.getPhone());
            afterLoanInfo.setCustRole(AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
            afterLoanInfo.setCertNo(custBaseInfo.getCertNo());
            afterLoanInfo.setCertEndDate(custBaseInfo.getCertEndDate());

            /**  申请贷款笔数 by ZC.GUO  **/
            List<BasicContractCustRelation> contractCustRelationList = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>query().lambda()
                    .eq(BasicContractCustRelation::getCustNo, custNo)
            );
            if (EmptyUtils.isNotEmpty(contractCustRelationList)) {
                for (BasicContractCustRelation custRelation : contractCustRelationList) {
                    CustBaseInfoVo custBaseInfoVo = new CustBaseInfoVo();
                    custBaseInfoVo.setContractNo(custRelation.getContractNo());
                    custBaseInfoVo.setCustRole(AfsEnumUtil.key(custRelation.getCustRole()));
                    afterLoanInfo.setCustRelation(custRelation.getCustRelation());
                    if (PersonRoleTypeEnum.MAIN_PERSON.equals(custRelation.getCustRole())) {
                        custBaseInfoVo.setDefaultFlag("1");
                    } else {
                        custBaseInfoVo.setDefaultFlag("0");
                    }
                    BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda().eq(BasicMainInfo::getContractNo, custRelation.getContractNo()));
                    if (EmptyUtils.isNotEmpty(mainInfo)) {
                        custBaseInfoVo.setContractStatus(AfsEnumUtil.key(mainInfo.getContractStatus()));
                    }
                    /**  贷款银行 by ZC.GUO  **/
                    BasicBankCard basicBankCard = basicBankCardService.getOne(Wrappers.<BasicBankCard>lambdaQuery()
                            .eq(BasicBankCard::getContractNo, contractNo)
                            .eq(BasicBankCard::getCertNo, custBaseInfo.getCertNo()));
                    if (EmptyUtils.isNotEmpty(basicBankCard)) {
                        custBaseInfoVo.setBankCode(basicBankCard.getBankCode());
                    }
                    afterLoanInfo.getCustBaseInfoList().add(custBaseInfoVo);
                }
                afterLoanInfo.setLoanNum(String.valueOf(contractCustRelationList.size()));
            }
        }
        /**  获取贷前的数据 by ZC.GUO  **/
        BasicCustBaseInfoVo beforeLoanInfo = new BasicCustBaseInfoVo();

        Map<String, String> headers = new HashMap<>(2);
//        headers.put("clientId",contractFeginConfig.getCaseClientId());
//        headers.put("clientSecret",contractFeginConfig.getCaseClientSecret());
        headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        IResponse<BasicCustBaseInfoVo> iResponse = caseForLoanBeforeInfoFeign.findCustInfoByQueryNo(contractNo, headers);
        if (CommonConstants.SUCCESS.equals(iResponse.getCode())) {
            beforeLoanInfo = iResponse.getData();
        }
        /**  贷前贷后都没有 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(afterLoanInfo.getCustName()) && EmptyUtils.isEmpty(beforeLoanInfo.getCustName())) {
            return IResponse.fail("查询错误");
        }
        /**  贷前贷后都有，以贷后为主，贷前数据合并 by ZC.GUO  **/
        else if (EmptyUtils.isNotEmpty(afterLoanInfo.getCustName()) && EmptyUtils.isNotEmpty(beforeLoanInfo.getCustName())) {
            afterLoanInfo.getCustBaseInfoList().addAll(beforeLoanInfo.getCustBaseInfoList());
            afterLoanInfo.setLoanNum(String.valueOf(Integer.valueOf(afterLoanInfo.getLoanNum()) + Integer.valueOf(beforeLoanInfo.getLoanNum())));
            return IResponse.success(afterLoanInfo);
        }
        /**  贷后有贷前没有 by ZC.GUO  **/
        else if (EmptyUtils.isNotEmpty(afterLoanInfo.getCustName()) && EmptyUtils.isEmpty(beforeLoanInfo.getCustName())) {
            return IResponse.success(afterLoanInfo);
        }
        /**  贷前有贷后没有 by ZC.GUO  **/
        else {
            return IResponse.success(beforeLoanInfo);
        }
    }

    @ApiOperation(value = "根据合同号码查询主共担基本信息（多条数据，列表格式）")
    @PostMapping("/custBaseInfoList")
    public IResponse<List<BasicCustBaseInfo>> custBaseInfoList(@RequestParam("contractNo") String contractNo) {
        List<BasicContractCustRelation> basicContractCustRelations = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo));
        List<BasicCustBaseInfo> basicCustBaseInfos = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(basicContractCustRelations)) {
            List<String> custNos = new ArrayList<>();
            for (BasicContractCustRelation cust : basicContractCustRelations) {
                custNos.add(cust.getCustNo());
            }
            List<BasicCustBaseInfo> list = basicCustBaseInfoService.list(Wrappers.<BasicCustBaseInfo>lambdaQuery().
                    in(BasicCustBaseInfo::getCustNo, custNos));
            if (EmptyUtils.isNotEmpty(basicCustBaseInfos)) {
                for (BasicCustBaseInfo base : list) {
                    for (BasicContractCustRelation cust : basicContractCustRelations) {
                        if (base.getCustNo().equals(cust.getCustNo())) {
                            base.setCustRole(cust.getCustRole());
                        }
                    }
                }
                basicCustBaseInfos.addAll(list);
            }
        }
        return IResponse.success(basicCustBaseInfos);
    }

    @ApiOperation(value = "根据合同号码查询主借人/共借人/担保人详细信息（custRole参数不传默认查询主借人）")
    @PostMapping("/custDetailInfo")
    public IResponse<BasicCustPersonalDetail> custDetailInfo(@RequestParam("contractNo") String contractNo,
                                                             @RequestParam(value = "custRole", defaultValue = "MAIN_PERSON") String custRole) {
        BasicContractCustRelation basicContractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo)
                .eq(BasicContractCustRelation::getCustRole, custRole));
        BasicCustPersonalDetail basicCustPersonalDetail = basicCustPersonalDetailService.getOne(Wrappers.<BasicCustPersonalDetail>lambdaQuery().
                eq(BasicCustPersonalDetail::getCustNo, basicContractCustRelation.getCustNo()));
        return IResponse.success(basicCustPersonalDetail);
    }

    @ApiOperation(value = "根据合同号码查询主共担详细信息")
    @PostMapping("/custDetailInfoList")
    public IResponse<List<BasicCustPersonalDetail>> custDetailInfoList(@RequestParam("contractNo") String contractNo) {
        List<BasicContractCustRelation> basicContractCustRelations = basicContractCustRelationService.list(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo));
        List<BasicCustPersonalDetail> basicCustBaseInfos = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(basicContractCustRelations)) {
            List<String> custNos = new ArrayList<>();
            for (BasicContractCustRelation cust : basicContractCustRelations) {
                custNos.add(cust.getCustNo());
            }
            List<BasicCustPersonalDetail> list = basicCustPersonalDetailService.list(Wrappers.<BasicCustPersonalDetail>lambdaQuery().
                    in(BasicCustPersonalDetail::getCustNo, custNos));
            if (EmptyUtils.isNotEmpty(basicCustBaseInfos)) {
                basicCustBaseInfos.addAll(list);
            }
        }
        return IResponse.success(basicCustBaseInfos);
    }

    @ApiOperation(value = "根据合同号码查询主共担联系电话信息（custRole参数不传默认查询主借人）")
    @PostMapping("/custContactInfoList")
    public IResponse<List<BasicCustContactDetails>> custContactInfoList(@RequestParam("contractNo") String contractNo,
                                                                        @RequestParam(value = "custRole", defaultValue = "MAIN_PERSON") String custRole) {
        BasicContractCustRelation basicContractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo)
                .eq(BasicContractCustRelation::getCustRole, custRole));
        List<BasicCustContactDetails> basicCustContactDetails = basicCustContactDetailsService.list(Wrappers.<BasicCustContactDetails>lambdaQuery().
                eq(BasicCustContactDetails::getCustNo, basicContractCustRelation.getCustNo())
        );
        List<BasicCustContactDetails> arrayList = new ArrayList();
        BasicCustContactDetails basicCustContactDetails1 = new BasicCustContactDetails();
        for (BasicCustContactDetails basicCustContactDetail : basicCustContactDetails) {
            if (basicCustContactDetail.getContactType().equals(ContactTypeEnum.WORK_PHONE)) {
                BeanUtils.copyProperties(basicCustContactDetail, basicCustContactDetails1);
            } else if (basicCustContactDetail.getContactType().equals(ContactTypeEnum.HOME_CONTACT)) {
                basicCustContactDetails1.setHomePhone(basicCustContactDetail.getContactNo());
            } else if (basicCustContactDetail.getContactType().equals(ContactTypeEnum.OTHER_CONTACT)) {
                basicCustContactDetails1.setOtherPhone(basicCustContactDetail.getContactNo());
            }
        }
        arrayList.add(basicCustContactDetails1);
        return IResponse.success(arrayList);
    }

    @ApiOperation(value = "根据合同号码查询主共担地址信息（custRole参数不传默认查询主借人）")
    @PostMapping("/custAddressInfoList")
    public IResponse<List<BasicCustAddressDetails>> custAddressInfoList(@RequestParam("contractNo") String contractNo,
                                                                        @RequestParam(value = "custRole", defaultValue = "MAIN_PERSON") String custRole) {
        BasicContractCustRelation basicContractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo)
                .eq(BasicContractCustRelation::getCustRole, custRole));
        List<BasicCustAddressDetails> basicCustAddressDetails = basicCustAddressDetailsService.list(Wrappers.<BasicCustAddressDetails>lambdaQuery().
                eq(BasicCustAddressDetails::getCustNo, basicContractCustRelation.getCustNo()));

        return IResponse.success(basicCustAddressDetails);
    }

    @ApiOperation(value = "根据合同号码查询紧急联系人信息")
    @PostMapping("/custContactsInfoList")
    public IResponse<List<BasicCustContacts>> custContactsInfoList(@RequestParam("contractNo") String contractNo) {
        List<BasicCustContacts> basicCustContactss = basicCustContactsService.list(Wrappers.<BasicCustContacts>lambdaQuery().
                eq(BasicCustContacts::getContractNo, contractNo));
        return IResponse.success(basicCustContactss);
    }

    @ApiOperation(value = "根据合同号码查询车辆资产信息列表数据")
    @PostMapping("/carDetailsList")
    public IResponse<List<BasicCarDetails>> carDetailsList(@RequestParam("contractNo") String contractNo) {
        List<BasicCarDetails> basicCarDetails = basicCarDetailsService.list(Wrappers.<BasicCarDetails>lambdaQuery().
                eq(BasicCarDetails::getContractNo, contractNo));
        return IResponse.success(basicCarDetails);
    }

    @ApiOperation(value = "根据合同号码查询罚息列表数据")
    @PostMapping("/findPenaltyInterest")
    public IResponse<List<BasicPenaltyInterest>> findPenaltyInterest(@RequestParam("contractNo") String contractNo) {
        List<BasicPenaltyInterest> basicPenaltyInterests = basicPenaltyInterestService.list(Wrappers.<BasicPenaltyInterest>lambdaQuery().
                eq(BasicPenaltyInterest::getContractNo, contractNo));
        return IResponse.success(basicPenaltyInterests);
    }

    @ApiOperation(value = "根据合同号码查询费用列表数据(去除罚息)")
    @PostMapping("/findExpense")

    public IResponse<List<BasicExpenseRecordVo>> findExpense(@RequestParam("contractNo") String contractNo) {
        List<BasicExpenseRecord> basicExpenseRecords = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>lambdaQuery().
                eq(BasicExpenseRecord::getContractNo, contractNo).ne(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty));
        BasicMainInfo basicMainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery()
                .eq(BasicMainInfo::getContractNo, contractNo));
        for (BasicExpenseRecord basicExpenseRecord : basicExpenseRecords) {
            basicExpenseRecord.setEndDate(basicMainInfo.getEndDate());
        }
        List<BasicExpenseRecordVo> list = new ArrayList<>();

        for (BasicExpenseRecord basicExpenseRecord : basicExpenseRecords) {
            BasicExpenseRecordVo basicExpenseRecordVo = new BasicExpenseRecordVo();
            BeanUtils.copyProperties(basicExpenseRecord, basicExpenseRecordVo);
            basicExpenseRecordVo.setExpireAmt(basicExpenseRecord.getCostAmt().subtract(basicExpenseRecord.getExemptedAmt()).subtract(basicExpenseRecord.getReceivedAmt()));
            list.add(basicExpenseRecordVo);

        }
        return IResponse.success(list);
    }


    @ApiOperation(value = "合同数据")
    @PostMapping("/deTs")
    public IResponse<List<BasicExpenseRecord>> deTs(@RequestParam("contractNo") String contractNo) {
        List<BasicExpenseRecord> basicExpenseRecords = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>lambdaQuery().
                eq(BasicExpenseRecord::getContractNo, contractNo).ne(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty));
        return IResponse.success(basicExpenseRecords);
    }


    @ApiOperation(value = "根据合同号码查询应收数据")
    @PostMapping("/financialAgree")
    public IResponse financialAgree(@RequestParam("contractNo") String contractNo) {
        ReceivableInfoVO receivableInfoVO = new ReceivableInfoVO();
        List<BasicReceiptRecord> basicReceiptRecords = basicReceiptRecordService.list(Wrappers.<BasicReceiptRecord>lambdaQuery().
                eq(BasicReceiptRecord::getContractNo, contractNo));
        List<BasicExpenseRecord> basicExpenseRecords = basicExpenseRecordService.list(Wrappers.<BasicExpenseRecord>lambdaQuery().
                eq(BasicExpenseRecord::getContractNo, contractNo));
        List<BasicRepaymentPlan> basicRepaymentPlans = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>lambdaQuery().
                eq(BasicRepaymentPlan::getContractNo, contractNo));
        BigDecimal BasicRepaymentPlan = BigDecimal.ZERO;
        for (BasicExpenseRecord basicExpenseRecord : basicExpenseRecords) {
            if (basicExpenseRecord.getCostType().equals(FeeTypeEnum.penalty)) {
                receivableInfoVO.setSumPenaltyAmt(receivableInfoVO.getSumPenaltyAmt().add(basicExpenseRecord.getRemainingAmt()));
            } else {
                receivableInfoVO.setSumRemainingAmt(receivableInfoVO.getSumRemainingAmt().add(basicExpenseRecord.getRemainingAmt()));
            }
//            for (BasicRepaymentPlan basicRepaymentPlan : basicRepaymentPlans) {
//                if (basicRepaymentPlan.getStatus().equals(RepaymentStatusEnum.UNPAID) || basicRepaymentPlan.getStatus().equals(RepaymentStatusEnum.OVERDUE)) {
//                    BasicRepaymentPlan.add(basicRepaymentPlan.getReceivableRent());
//                    receivableInfoVO.setSumReceivablePrinciple(receivableInfoVO.getSumReceivablePrinciple().add(basicRepaymentPlan.getReceivablePrinciple()));
//                    receivableInfoVO.setSumReceivableInterest(receivableInfoVO.getSumReceivableInterest().add(basicRepaymentPlan.getReceivableInterest()));
//                }
//            }
//            receivableInfoVO.setOutstandingTotalAmt(BasicRepaymentPlan.add(receivableInfoVO.getSumPenaltyAmt().add(receivableInfoVO.getSumRemainingAmt())));
            for (BasicReceiptRecord basicReceiptRecord : basicReceiptRecords) {
                receivableInfoVO.setSumUnusedAmt(receivableInfoVO.getSumUnusedAmt().add(basicReceiptRecord.getUnusedAmt()));
            }

        }
        for (com.ruicar.afs.cloud.basic.common.entity.BasicRepaymentPlan basicRepaymentPlan : basicRepaymentPlans) {
            if (basicRepaymentPlan.getStatus().equals(RepaymentStatusEnum.UNPAID) || basicRepaymentPlan.getStatus().equals(RepaymentStatusEnum.OVERDUE)) {
                BasicRepaymentPlan.add(basicRepaymentPlan.getReceivableRent());
                receivableInfoVO.setSumReceivablePrinciple(receivableInfoVO.getSumReceivablePrinciple().add(basicRepaymentPlan.getReceivablePrinciple()));
                receivableInfoVO.setSumReceivableInterest(receivableInfoVO.getSumReceivableInterest().add(basicRepaymentPlan.getReceivableInterest()));
            }
        }
        receivableInfoVO.setOutstandingTotalAmt(BasicRepaymentPlan.add(receivableInfoVO.getSumPenaltyAmt().add(receivableInfoVO.getSumRemainingAmt()).add(receivableInfoVO.getSumReceivablePrinciple()).add(receivableInfoVO.getSumReceivableInterest())));
        return IResponse.success(receivableInfoVO);
    }

    @ApiOperation(value = "根据合同号查询客户姓名")
    @PostMapping("/getCustName")
    public IResponse<BasicCustBaseInfo> getCustName(@RequestParam("contractNo") String contractNo) {
        BasicContractCustRelation basicContractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>query().lambda()
                .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
                .eq(BasicContractCustRelation::getContractNo, contractNo)
        );
        BasicCustBaseInfo basicCustBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>query().lambda()
                .eq(BasicCustBaseInfo::getCustNo, basicContractCustRelation.getCustNo())
        );
        return IResponse.success(basicCustBaseInfo);
    }

}
